package com.gssbh.framework.toolkit.web;


import com.gssbh.framework.toolkit.web.constant.ApiPathConstants;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Objects;


public class SecurityHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
       boolean result = handleRequest(request,response,handler);
       if(!result){
           response.getWriter().println("can not allow access");
       }
       return result;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    private boolean handleRequest(HttpServletRequest request, HttpServletResponse response,
                                  Object handler){
        String servletPath = request.getServletPath();
        if(Objects.isNull(servletPath)){
            return false;
        }
        // 公开API
        if(servletPath.endsWith(ApiPathConstants.VISIBLE_API_SUFFIX)){
            return true;
        }

        return false;
    }
}
